﻿CREATE PROCEDURE [dbo].[usp_set_accesspolicy]
	@pUserOrGroupName nvarchar(100)
	, @pAccessPolicy xml
	, @pUser nvarchar(50)
AS

-- CHECK IF POLICY EXISTS FOR THIS USER/GROUP
IF NOT EXISTS(
	SELECT Id
	FROM [dbo].[AccessPolicy]
	WHERE UserOrGroupName = @pUserOrGroupName
)
	BEGIN

		INSERT INTO [dbo].[AccessPolicy] (
			Id
			, UserOrGroupName
			, AccessPolicy
			, LastModifiedOn
			, LastModifiedBy)
		VALUES(
			NEWID()
			, @pUserOrGroupName
			, @pAccessPolicy
			, GETDATE()
			, @pUser) 
	END

ELSE
	BEGIN
		UPDATE [dbo].[AccessPolicy]
		SET 
			AccessPolicy = @pAccessPolicy
			, LastModifiedBy = @pUser
			, LastModifiedOn = GETDATE()
		WHERE UserOrGroupName = @pUserOrGroupName
	END


SELECT Id
	FROM [dbo].[AccessPolicy]
	WHERE UserOrGroupName = @pUserOrGroupName

